package servlets;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import models.AccountManagement;
import models.AnnounceManagement;

/**
 * Servlet implementation class DangNhap
 */
public class Login extends HttpServlet {
	HttpSession session;
	String userId, password, userErr;
	AccountManagement am;
	static int counter;

	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		session = request.getSession();
		String userId = request.getParameter("username");
		String password = request.getParameter("password");
		String userErr = "";
		try {
			AnnounceManagement anm = new AnnounceManagement();
			ArrayList<String> contents = anm.getContents();
			session.setAttribute("contents", contents);
		} catch (ClassNotFoundException | SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			am = new AccountManagement(userId);
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (userErr.equals("") && !am.checkUser(userId, password))
			userErr = "Sai thông tin đăng nhập";
		String url = "/Home";
		if (userErr.length() > 0) {
			url = "/login.jsp";
			if (userErr.length() > 0)
				session.setAttribute("userErr", userErr);
			counter++;
		}

		session.setAttribute("counter", counter);
		session.setAttribute("userId", am.getId());
		session.setAttribute("userName", am.getName());
		RequestDispatcher rd = getServletContext().getRequestDispatcher(url);
		rd.forward(request, response);

	}
}
